<?php
/*
 * Theme Name: 960Base Theme SIMPLE
 * Theme URI: http://960basetheme.kiuz.it
 * Description: Wordpress theme based on 960 Grid System
 * Author: Domenico Monaco
 * Author URI: http://www.kiuz.it
 * Version: 1.0.0 BETA
 */


/* Buzzr */
define('BUZZR_URL', get_bloginfo('url'));
define('BUZZR_WP_URL', get_bloginfo('wpurl'));
define('BUZZR_THEME_URL', get_stylesheet_directory_uri());
/* Buzzr */

if ( function_exists('register_sidebar') ){

/*
register_sidebar(array(
		'name' => 'Header Region 0',
		'before_widget' => '<div id="%1$s" class="widget-header %2$s"><div class="box">',
		'after_widget' => '</div></div></div>',
		'before_title' => '<h2><a href="#">',
		'after_title' => '</a></h2><div>'
		));
*/

register_sidebar(array(
		'name' => 'Sidebar 1',
		'before_widget' => '<div id="%1$s" class="widget %2$s"><div class="box"><div>',
		'after_widget' => '</div></div></div>',
		'before_title' => '<h2>',
		'after_title' => '</h2>'
		));
	
/*
register_sidebar(array(
		'name' => 'Content Region 0',
		'before_widget' => '<div id="%1$s" class="widget-content %2$s"><div class="box">',
		'after_widget' => '</div></div></div>',
		'before_title' => '<h2><a href="#">',
		'after_title' => '</a></h2><div>'
		));

register_sidebar(array(
		'name' => 'Footer Region 0',
		'before_widget' => '<div id="%1$s" class="widget-footer %2$s"><div class="box">',
		'after_widget' => '</div></div></div>',
		'before_title' => '',
		'after_title' => '<div>'
		));
*/	
register_sidebar(array(
		'name' => 'Footer Region 1',
		'before_widget' => '<div id="%1$s" class="widget-footer %2$s"><div class="box"><div>',
		'after_widget' => '</div></div></div>',
		'before_title' => '',
		'after_title' => ''
		));
	
register_sidebar(array(
		'name' => 'Footer Region 2',
		'before_widget' => '<div id="%1$s" class="idget-footer %2$s"><div class="box"><div>',
		'after_widget' => '</div></div></div>',
		'before_title' => '',
		'after_title' => ''
		));
	
register_sidebar(array(
		'name' => 'Footer Region 3',
		'before_widget' => '<div id="%1$s" class="idget-footer %2$s"><div class="box"><div>',
		'after_widget' => '</div></div></div>',
		'before_title' => '',
		'after_title' => ''
		));
	
}

/* Buzzr Hide Admin Bar */

// Add ID and CLASS attributes to the first <ul> occurence in wp_page_menu
function add_menuclass($ulclass) {
return preg_replace('/<ul>/', '<ul class="nav main">', $ulclass, 1);
}
add_filter('wp_page_menu','add_menuclass');


add_filter( 'show_admin_bar', '__return_false' );
add_action( 'admin_print_scripts-profile.php', 'hide_admin_bar_prefs' );
function hide_admin_bar_prefs() { ?>
<style type="text/css">
    .show-admin-bar { display: none; }
</style>
<?php
}
/* Buzzr Hide Admin Bar */

/* Buzzr Remove WordPress Generated content from Head */
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'start_post_rel_link');
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'adjacent_posts_rel_link');
/* Buzzr Remove WordPress Generated content from Head */

/* Buzzr Facebook Like iFrame */
function buzzr_fb_like($like_url = '',$faces = ''){
   if(empty($like_url)){
 		echo '<iframe src="http://www.facebook.com/plugins/like.php?href=http://www.facebook.com/BuzzrIndia&amp;layout=button_count&amp;width=200&amp;action=like&amp;font=segoe+ui&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:20px; margin-top: 15px" allowTransparency="true"></iframe>';  	
   }else{
	   if(!empty($faces)){
	      echo '<iframe src="http://www.facebook.com/plugins/like.php?href=http://buzzr.in'.$like_url.'&amp;show_faces=true&amp;width=450&amp;action=like&amp;font=segoe+ui&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:250px; height:100px;" allowTransparency="true"></iframe>';
	   }
	   else{
	      echo '<iframe src="http://www.facebook.com/plugins/like.php?href=http://buzzr.in'.$like_url.'&amp;layout=button_count&amp;width=450&amp;action=like&amp;font=segoe+ui&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:20px;" allowTransparency="true"></iframe>';
	   }
   } 
}
/* Buzzr Facebook Like iFrame */

/* Buzzr FiX End Date Check in SQL POD Queries */
function fix_date(){
 $string = "DATE_ADD(NOW(), INTERVAL '05:30' HOUR_MINUTE)";
 return $string;
}
/* Buzzr FiX End Date Check in SQL POD Queries */

/* Buzzr Get City Names */
function get_buzzr_cities($name = ''){
	$city_pod = new Pod('city');
	$city_pod->page = 1;
	$city_pod->search = false;
	if(empty($name)){
		$city_pod->findRecords('name ASC', -1);
	}else{
		$city_pod->findRecords('name ASC', -1,"t.name = '$name'");
	}
	unset($buzzr_cities);
	$i = 0;
	while($city_pod->fetchRecord()){
		$cities[$i]['id'] = $city_pod->get_field('id');
		$cities[$i]['name'] = $city_pod->get_field('name');
		$i++;
	}
	return $cities;	
}
/* Buzzr Get City Names */

/* Buzzr Get Category Array either one field or all */
function get_buzzr_categories($field = '', $where = ''){
	$category_pod = new Pod('category');
	$category_pod->page = 1;
	$category_pod->search = false;
	$category_pod->findRecords('name ASC', -1, $where);
	unset($buzzr_categories);
	$i = 0;
	while($category_pod->fetchRecord()){
		if(!empty($field)){
			$categories[] = $category_pod->get_field($field);
		}else{
			$categories[$i]['id'] = $category_pod->get_field('id');
			$categories[$i]['name'] = $category_pod->get_field('name');
			$categories[$i]['url'] = $category_pod->get_field('url');
		}
		$i++;
	}
	return $categories;
}
/* Buzzr Get Category Array either one field or all */

/* Buzzr Get Tags by Record set in different formats */
function get_deal_tags($deal_record,$separator = ' ',$link = false){

  unset($tags);
  unset($deal_tags['name']);
  $deal_tags['name'] = $deal_record->get_field('tag_pick.name');
  
  if($link == true){
    $deal_tags['name'] = $deal_record->get_field('tag_pick.name');
  }
  
  if(!empty($deal_tags['name'])){
    $count = count($deal_tags['name']);
    if($count == '1'){
        $tags = stripslashes($deal_tags['name']);
    }
    else{
      for($i=0;$i<$count;$i++){
          $tags .= stripslashes($deal_tags['name'][$i]);
          if($i != ($count - 1)){
              $tags .= $separator;
          }
      }
    }
  }
  return $tags;
}
/* Buzzr Get Tags by Record set in different formats */

/* Buzzr Encyption Functions Key = 1b2u3z4z5r6 */
function decrypt($string, $key){
    $string = str_replace('WPT', '/', $string);
    $string = str_replace('W1PT', '+', $string);
    $string = base64_decode($string);
    /* Open the cipher */
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CFB, '');
    /* Get IV  and keysize length */
    $iv_size = mcrypt_enc_get_iv_size($td);
    $iv = substr($string,0,$iv_size);
    $string = substr($string,$iv_size);
    $ks = mcrypt_enc_get_key_size($td);
    /* Create key */
    $key = substr(md5($key), 0, $ks);
    /* Initialize encryption module for decryption */
    mcrypt_generic_init($td, $key, $iv);
    /* Decrypt encrypted string */
    $decrypted = mdecrypt_generic($td, $string);
    /* Terminate decryption handle and close module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    return $decrypted;
}

function encrypt($string, $key){
    /* Open the cipher */
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CFB, '');
    /* Create the IV and determine the keysize length, use MCRYPT_RAND on Windows instead  and MCRYPT_DEV_RANDOM on Linux*/
    $iv_size = mcrypt_enc_get_iv_size($td);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);
    /* Create key */
    $key = substr(md5($key), 0, $ks);
    /* Intialize encryption */
    mcrypt_generic_init($td, $key, $iv);
    /* Encrypt data */
    $encrypted = mcrypt_generic($td, $string);
    /* Terminate encryption handle and close module */
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    $encrypted = $iv.$encrypted;
    $return = base64_encode($encrypted);
    $return = str_replace('/', 'WPT', $return);
    $return = str_replace('+', 'W1PT', $return);
    return $return;
}
/* Buzzr Encyption Functions */


/* Buzzr Debug */
function printr($var, $exit = null){
    $output = print_r($var, true);
    $output = str_replace("\n", "<br>", $output);
    $output = str_replace(' ', '&nbsp;', $output);
    echo "<div style='font-family:courier;'>--<pre>$output</pre>--</div>";
    if($exit == 1) { 
    exit(); }
}
/* Buzzr Debug */

function init_scripts(){
  if(!is_admin()){
    
  	/* Scripts */
  	wp_deregister_script('thickbox');
  	wp_deregister_script('l10n');
  	
  	wp_deregister_script('jquery');
    wp_register_script('jquery','https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js', array(),'1.5.2',false);
    
    wp_deregister_script('jquery-ui-core');
    wp_register_script('jquery-ui',('https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js'), array(),'1.8.14',true);
    
    wp_register_script('google-maps',('http://maps.google.com/maps/api/js?sensor=false'), array(),'3',true);
    wp_register_script('jquery-ui-maps',(BUZZR_THEME_URL.'/js/jquery.ui.map.min.js'), array(),'2',true);
    
    wp_register_script('homepage',(BUZZR_THEME_URL.'/js/home.js'), array(),'1.0',true);
    wp_register_script('global',(BUZZR_THEME_URL.'/js/global.js'), array(),'1.0',false);
    wp_register_script('list-grid',(BUZZR_THEME_URL.'/js/list-grid.js'), array(),'1.0',false);
    wp_register_script('list-map',(BUZZR_THEME_URL.'/js/list-map.js'), array(),'1.0',true);
    wp_register_script('brands-tabs',(BUZZR_THEME_URL.'/js/brands_tabs.js'), array(),'1.0',true);
   // wp_register_script('plus-one',('https://apis.google.com/js/plusone.js'), array(),'1.0',true);
    wp_register_script('color-picker',(BUZZR_WP_URL.'/wp-content/pfiles/jscolor/jscolor.js'), array(),'1.0',true);
    wp_register_script('get-widget',(BUZZR_THEME_URL.'/js/getwidget.js'), array(),'1.0',true);
    wp_register_script('deals-detail-map',(BUZZR_THEME_URL.'/js/deals_detail.js'), array(),'1.0',true);
    /* Scripts */
    
    /* Styles */
    wp_deregister_style('thickbox');
    
    wp_register_style('homepage',(BUZZR_THEME_URL.'/css/home.css'));
    wp_register_style('brands_tabs',(BUZZR_THEME_URL.'/css/brands_tabs.css'));
    wp_register_style('list',(BUZZR_THEME_URL.'/css/list.css'));
    wp_register_style('stores',(BUZZR_THEME_URL.'/css/stores.css'));
    wp_register_style('google_maps',(BUZZR_THEME_URL.'/css/map.css'));
    wp_register_style('dailydeals',(BUZZR_THEME_URL.'/css/daily.css'));
    wp_register_style('member_tabs',(BUZZR_THEME_URL.'/css/member_tabs.css'));
    wp_register_style('leaderboard',(BUZZR_THEME_URL.'/css/leaderboard.css'));
    wp_register_style('getwidget',(BUZZR_THEME_URL.'/css/getwidget.css'));
    wp_register_style('deals_detail',(BUZZR_THEME_URL.'/css/deal_details.css'));
    /* Styles */
  }
}
add_action('init', 'init_scripts');

function buzzr_print_scripts(){
  wp_enqueue_script('jquery');
  wp_enqueue_script('jquery-ui');
  wp_enqueue_script('global');
  
  if(is_pod_page('deals/*')){
  	wp_enqueue_script('google-maps');
  	wp_enqueue_script('jquery-ui-maps');
  	wp_enqueue_script('deals-detail-map');
  }
  
  if(!is_pod_page('editprofile')){
      wp_dequeue_script('fep-forms-passmeter');
      wp_dequeue_script('fep-forms-script');
  }
  
  if(is_pod_page() || is_home()){
    wp_dequeue_script('sociable-addtofavorites');
  }
  
  if(!is_page(array('contact-us','feedback','advertisers','write-for-us')) && !is_pod_page('advertisers/dashboard')){
  	wp_dequeue_script('contact-form-7');
  }
  
  if(is_home()){
  	wp_enqueue_script('homepage');
  	wp_enqueue_script('google-maps');
  	wp_enqueue_script('jquery-ui-maps');
  }
  
  if(is_pod_page('localoffers/*') || is_pod_page('localoffers/*/c-*') || is_pod_page('localoffers')){
  //	wp_enqueue_script('plus-one');
  	wp_enqueue_script('list-map');
  	wp_enqueue_script('google-maps');
  	wp_enqueue_script('jquery-ui-maps');	
  }
  
  if(is_pod_page('c-*')|| is_pod_page('deals/*') || is_pod_page('coupons') || is_pod_page('deals') || is_pod_page('stores') || is_pod_page('brands/*') || is_pod_page('deals') || is_search() || is_pod_page('t-*') || is_pod_page('member/*')  || is_pod_page('dailydeals/*') || is_pod_page('c-flight-offers') || is_pod_page('c-hotel-offers') || is_pod_page('c-vacation-offers') || is_pod_page('deals-popular') || is_pod_page('deals-expiringsoon')  || is_pod_page('deals/*')  || is_pod_page('coupons/*') || is_pod_page('coupons/online')){
  //	wp_enqueue_script('plus-one');
  	wp_enqueue_script('list-grid');	
  }
  
  if(is_pod_page('brands/*') || is_pod_page('t-*') || is_pod_page('member/*')){
  	wp_enqueue_script('brands-tabs');
  }
  
  if(is_pod_page('getwidget')){
  	wp_enqueue_script('color-picker');
  	wp_enqueue_script('get-widget');
  }
}
add_action('wp_print_scripts', 'buzzr_print_scripts');


function buzzr_print_styles(){
  
  if(is_pod_page('deals/*')){
  	wp_enqueue_style('deals_detail');
  }
	
  if(!is_pod_page('editprofile')){
      wp_dequeue_style('fep-forms-style');
      wp_dequeue_style('fep-forms-passmeter');
  }
  
  if(!is_page(array('contact-us','feedback','advertisers','write-for-us')) && !is_pod_page('advertisers/dashboard')){
  	wp_deregister_style('contact-form-7');
  }
  
  if(is_pod_page() || is_home()){
    wp_dequeue_style('sociable-front-css');
  }
  
  if(is_pod_page() || is_home()){
    remove_action('wp_footer', array('AWP','print_header'));
  }
   
  if(is_home()){
	wp_enqueue_style('homepage');
  }
  
  if(is_search() || is_pod_page('deals/*') || is_pod_page('coupons') || is_pod_page('deals/*') || is_pod_page('deals') || is_pod_page('brands/*') || is_pod_page('c-*') || is_pod_page('localoffers') || is_pod_page('localoffers/*') || is_pod_page('localoffers/*/c-*') || is_pod_page('stores') || is_pod_page('t-*') || is_pod_page('member/*') || is_pod_page('dailydeals/*') || is_pod_page('c-flight-offers') || is_pod_page('c-hotel-offers') || is_pod_page('c-vacation-offers') || is_pod_page('deals-popular') || is_pod_page('deals-expiringsoon')  || is_pod_page('coupons/*') || is_pod_page('coupons/online')){
  	wp_enqueue_style('list');
  }
  
  if(is_pod_page('stores')){
  	wp_enqueue_style('stores');
  }
  
  if(is_pod_page('brands/*') || is_pod_page('t-*')){
  	wp_enqueue_style('brands_tabs');
  }
  
  if(is_pod_page('localoffers/*') || is_pod_page('localoffers/*/c-*') || is_pod_page('localoffers')){
  	wp_enqueue_style('google_maps');
  }
  
  if(is_pod_page('dailydeals') || is_pod_page('dailydeals-new')){
  	wp_enqueue_style('dailydeals');
  }

  if(is_pod_page('member/*')){
  	wp_enqueue_style('member_tabs');
  }
  
  if(is_pod_page('leaderboard')){
  	wp_enqueue_style('leaderboard');
  }
  
  if(is_pod_page('getwidget')){
  	wp_enqueue_style('getwidget');
  }
}
add_action('wp_print_styles', 'buzzr_print_styles');

/* Buzzr Get Users Pod ID or if WP_ID is supplied */
function get_buzzr_users_pod_id($id = '',$field = ''){
	$users = new Pod('users');
	$users->page = 1;
	$users->search = false;
	
	if(empty($id)){
		global $current_user;
		get_currentuserinfo();
		$user_wp_id = $current_user->ID;
		$users->findRecords('id DESC',1,"wp_user.ID='$user_wp_id'");
	}else{
		$users->findRecords('id DESC',1,"wp_user.ID='$id'");
	}
	
	while($users->fetchRecord()){
		if(empty($field)){
			$users_pod_id = $users->get_field('id');
		}else{
			$users_pod_id = $users->get_field($field);
		}
	}
	
	return $users_pod_id; 
}
/* Buzzr Get Users Pod ID */

/* Buzzr Curl Download Page */ 
function buzzr_download_page($path){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$path);
        curl_setopt($ch, CURLOPT_FAILONERROR,1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 45);
        $retValue = curl_exec($ch);                      
        curl_close($ch);
        return $retValue;
}
/* Buzzr Curl Download Page */

/* Code to Calculate time since */
function buzzr_time_since($time_to_calc){
  $original = date("U", strtotime($time_to_calc));
  $today = time();
      
  // array of time period chunks
  $chunks = array(
      (60 * 60 * 24 * 365),
      (60 * 60 * 24 * 30),
      (60 * 60 * 24 * 7),
      (60 * 60 * 24),
      (60 * 60),
      (60),
      (1)
  );
  
  $since = $today - $original;
  
  for ($i = 0, $j = count($chunks); $i < $j; $i++) {
      $seconds = $chunks[$i];
  
      if (0 != $count = floor($since / $seconds))
          break;
  }
  
  $trans = array(
      _n('%d year', '%d years', $count),
      _n('%d month', '%d months', $count),
      _n('%d week', '%d weeks', $count),
      _n('%d day', '%d days', $count),
      _n('%d hour', '%d hours', $count),
      _n('%d minute', '%d minutes', $count),
      _n('%d second', '%d seconds', $count)
  );
  
  if ('0000-00-00 00:00:00' == $value) {
      $time_since = 'never';
  }
  elseif ($today == $original) {
      $time_since = 'less than a second';
  }
  else {
      $time_since = sprintf($trans[$i], $count);
  }
return $time_since;
}
/* Code to Calculate time since */

/* Subscribe to the Daily Deals newsletter, jus provide email, city id 
& only via registration process the isers_pod_id is given directly */
function buzzr_subscribe_newsletter($email,$city = '',$user_pod_id = ''){
	
	$api = new PodAPI();
	$columns_newsletter['name'] = $email;
	$slug = sanitize_title($columns_newsletter['name']); 
	$unique_slug = pods_unique_slug($columns_newsletter['name'],'slug','newsletter','31');
    
    /* MadMimi Integration For Daily Newsletter */
    if(!empty($city)){
        global $wpdb;
        require_once(WP_PLUGIN_DIR.'/MadMimi.class.php');
        
        $query = "SELECT name FROM wp_pod_tbl_city WHERE id={$city}";
        $daily_city = $wpdb->get_var($query);
        $mailer = new MadMimi('chetan.bhatia@enthrallmedia.com ', 'e41020cad61e0008fe2796c739415a45');
        $user = array('email' => $email, 'city' => $daily_city, 'Daily' => 'yes', 'add_list' => 'Super List');
        $mailer->AddUser($user);
    }
    /* MadMimi Integration For Daily Newsletter */
    
	if($slug == $unique_slug){
		
		$columns_newsletter['slug'] = $slug;
		$columns_newsletter['cities'] = $city;
		
		$category_ids = get_buzzr_categories('id','t.is_local = 1 OR t.is_daily = 1');
		$category_ids = implode(',',$category_ids);
		
		$columns_newsletter['categories'] = $category_ids;
		$columns_newsletter['daily'] = 1;
		$columns_newsletter['weekly'] = 1;
		
		if(email_exists($columns_newsletter['name'])){
			$wp_id = email_exists($columns_newsletter['name']);
			$users_pod_item = get_buzzr_users_pod_id($wp_id);
			$columns_newsletter['user'] = $users_pod_item;
		}
		
		if(!empty($user_pod_id)){
			$columns_newsletter['user'] = $user_pod_id;
		}
		
		$params_newsletter = array('datatype' => 'newsletter', 'columns' => $columns_newsletter);
		$newsletter_pod_item = $api->save_pod_item($params_newsletter);
	    if(!empty($newsletter_pod_item)){
	      return 'success';
		}
		
    }else{
	    $newsletter_pod_item = new Pod('newsletter',$slug);
    	$newsletter_id = $newsletter_pod_item->get_field('id');
    	$columns_users_pod['user'] = $user_pod_id;
    	$params_users_pod = array('datatype' => 'newsletter','tbl_row_id' => $newsletter_id, 'columns' => $columns_users_pod);
    	$api->save_pod_item($params_users_pod);
    	return 'exists';
	}
}
/* Subscribe to the Daily Deals newsletter */


function users_pod_name()
{
if(is_user_logged_in())
{
global $current_user;
get_currentuserinfo();
$wp_id = $current_user->ID;
$user_data = get_userdata($wp_id);
$username = ucwords($user_data->user_login);
//$first = ucwords($user_data->first_name);
//$last = ucwords($user_data->last_name);

$users = new Pod('users');
$users->page = 1;
$users->search = false; 
$users->findRecords('id DESC', 1, "wp_user.id ='$wp_id'");
while($users->fetchRecord())
{
$user_slug = $users->get_field('slug');
$user_pod_id = $users->get_field('id');
}

$points = new Pod('points');
$points->page = 1;
$points->search = false; 
$points->findRecords('id DESC', 1, "user.id ='$user_pod_id'");
while($points->fetchRecord())
{
$points_pod_id = $points->get_field('id');
$points_login = $points->get_field('login');
}

if(strlen($user_slug) <= 0 || $user_slug < 0 || $user_slug == '-1')
{
  $api = new PodAPI();
  $columns_user['name'] = $username;
  $columns_user['slug'] = sanitize_title($columns_user['name']);
  $params = array('datatype' => 'users','tbl_row_id' => $user_pod_id ,'columns' => $columns_user);
  $api->save_pod_item($params);
  
  $columns_points['name'] = $columns_user['name'];
  $columns_points['slug'] = sanitize_title($columns_user['name']);
  $params_points = array('datatype' => 'points','tbl_row_id' => $points_pod_id ,'columns' => $columns_points);
  $api->save_pod_item($params_points);  
}

if(isset($_COOKIE['buzzr_refer']))
{
  $referer_slug = $_COOKIE['buzzr_refer'];
  $pastdate = mktime(0,0,0,1,1,1970);
  setcookie("buzzr_refer","",$pastdate);
  $referer = new Pod('users',$referer_slug);
  $referer_id = $referer->get_field('id');
  $referer_ref_points = $referer->get_field('points.referral');
  $referer_ref_points_id = $referer->get_field('points.id');
  $columns_user['referred_by_user'] = $referer_id;
  
  $api = new PodAPI();
  $params = array('datatype' => 'users','tbl_row_id'=>$user_pod_id,'columns' => $columns_user);
  $api->save_pod_item($params);
}
    
    
if(!empty($referer_id))
{
    $api = new PodAPI();
    $columns_referer['users_referred'] = $user_pod_id;//new user's pod item id
    $params_ref = array('datatype' => 'users','tbl_row_id'=>$referer_id,'columns' => $columns_referer);
    $api->save_pod_item($params_ref);
    
    $columns_ref_points['referral'] = ($referer_ref_points + 300);
    $params_ref_points = array('datatype' => 'points','tbl_row_id'=>$referer_ref_points_id,'columns' => $columns_ref_points);
    $api->save_pod_item($params_ref_points);
} 

}
}
add_action('wp_head', 'users_pod_name');
/* EOF Custom Buzzr */

/* BOF Custom Buzzr */
/* Function hooks into the WP-Register's Hook to check if user 
loggin in has a pod item, if not creates one for the user */

function users_new_pod_item_wp($user_id)
{
  $is_buzzr_user = get_buzzr_users_pod_id($user_id);
  $api = new PodAPI();
  if(empty($is_buzzr_user)){
    date_default_timezone_set('Asia/Kolkata');

  	$user_obj = get_userdata($user_id);
    $username = ucwords($user_obj->user_login);
    $user_email = $user_obj->user_email;
    $user_city = get_user_meta($user_id,'city',true);
    if(empty($user_city)){
        $user_city = "Mumbai";
    }
    
    /* User Pod */
    $columns_user['name'] = $username; 
    $columns_user['wp_user'] =  $user_id;
    $columns_user['slug'] =  "";
    $columns_user['login_day'] = date('Y-m-d');
	$columns_user['last_login'] = date('Y-m-d H:i:s');
    $params = array('datatype' => 'users','columns' => $columns_user);
    $user_pod_id = $api->save_pod_item($params);
    /* User Pod */
    
    /* MadMimi Integration */
    require_once(WP_PLUGIN_DIR.'/MadMimi.class.php');
    $mailer = new MadMimi('chetan.bhatia@enthrallmedia.com ', 'e41020cad61e0008fe2796c739415a45');
    $user = array('email' => $user_email, 'city' => $user_city, 'daily' => 'no', 'add_list' => 'Super List');
    $mailer->AddUser($user);
    /* MadMimi Integration */
    
    /* Points Pod */
    $columns_points['name'] = $columns_user['name'];
    $columns_points['slug'] = "";
    $columns_points['registration'] = '1000';
    $columns_points['login'] = '0';
    $columns_points['comments'] = '0';
    $columns_points['deals'] = '0';
    $columns_points['like_fb'] = '0';
    $columns_points['vote'] = '0';
    $columns_points['feedback'] = '0';
    $columns_points['referral'] = '0';
    $columns_points['user'] = $user_pod_id; 
    $params_points = array('datatype' => 'points','columns' => $columns_points);
    $api->save_pod_item($params_points);
    /* Points Pod */
    
    /* Newsletter Pod */
    $daily = get_user_meta($user_id,'get_the_best_deals_in_your_email',true);
    if($daily == 'Signup for our daily deals newsletter'){
	    
    	$daily_city_name = get_user_meta($user_id,'city',true);
	    if(!empty($daily_city_name)){
	      $daily_city = new Pod('city');
	      $daily_city->page = 1;
	      $daily_city->search = false; 
	      $daily_city->findRecords('id ASC', -1, "t.name ='$daily_city_name'");
	      while($daily_city->fetchRecord()){
	        $daily_city_id = $daily_city->get_field('id');
	      }
	    }
	    buzzr_subscribe_newsletter($user_email,$daily_city_id,$user_pod_id);
	    session_start();
	    $_SESSION['daily_signup'] = 1;
	    $_SESSION['daily_email'] = $user_email;   
    }else{
    	buzzr_subscribe_newsletter($user_email,'',$user_pod_id);
    }
    /* Newsletter Pod */
    
  } 
}
add_action('user_register', 'users_new_pod_item_wp');

/* BOF Custom Buzzr */
/* Function basically detects if user is logged in n assigns points for login per day
detects if the user has a points pod too, if not creates one n modifies the necessary 
user pod details too */

function logged_in_points(){
    if(is_user_logged_in()){
      global $current_user;
      get_currentuserinfo();
      $wp_id = $current_user->ID;
      $user_roles = $current_user->roles;
      $user_role = array_shift($user_roles);

      if ($user_role == 'administrator' || $user_role == 'consumer')
      {
      date_default_timezone_set('Asia/Kolkata');
      $users = new Pod('users');
      $users->page = 1;
      $users->search = false;
      $users->findRecords('id DESC', "1", "wp_user.id ='$wp_id'");
      while ($users->fetchRecord())
      {
          $users_id = $users->get_field('id');
  	      $users_name = $users->get_field('name');
  	      $login_day = $users->get_field('login_day');
      }
  
      $points = new Pod('points');
      $points->page = 1;
      $points->search = false;
      $points->findRecords('id DESC', "1", "user.id ='$users_id'");
      
      $pod_item_exits = $points->getTotalRows();
  
      if($pod_item_exits == 1)
      {
  	    while ($points->fetchRecord())
  	    {
      		$id = $points->get_field('id');
      		$login_points = $points->get_field('login');
  	    }
  
        if(empty($login_day))
        {
          $api = new PodAPI();
    	    $columns_points['login'] = ($login_points + 50);
    	    $params = array('datatype' => 'points','tbl_row_id' => $id, 'columns' => $columns_points);
    	    $api->save_pod_item($params);
    	    $login_day_mod = date('Y-m-d');
        }
        elseif(strtotime($login_day) < strtotime(date('Y-m-d')))
        {
          $api = new PodAPI();
    	    $columns_points['login'] = ($login_points + 50);
    	    $params = array('datatype' => 'points','tbl_row_id' => $id, 'columns' => $columns_points);
    	    $api->save_pod_item($params);
    	    $login_day_mod = date('Y-m-d');
        }
        
        $api = new PodAPI();
  	    if(!empty($login_day_mod))
  	    {
          $columns_consumer['login_day'] = $login_day_mod; 
        }
        $columns_consumer['last_login'] = date('Y-m-d H:i:s');
  	    $params = array('datatype' => 'users','tbl_row_id' => $users_id, 'columns' => $columns_consumer);
  	    $api->save_pod_item($params);
      }
      else
      {
     	 $api = new PodAPI();
  	   $columns_points['name'] = $users_name;
  	   $columns_points['slug'] = $users_name;
  	   $columns_points['registration'] = '1000';
  	   $columns_points['login'] = '50';
  	   $columns_points['comments'] = '0';
  	   $columns_points['deals'] = '0';
  	   $columns_points['like_fb'] = '0';
  	   $columns_points['vote'] = '0';
  	   $columns_points['feedback'] = '0';
  	   $columns_points['referral'] = '0';
  	   $columns_points['user'] = $users_id;
  	   $params = array('datatype' => 'points','columns' => $columns_points);
  	   $api->save_pod_item($params);
  	   
  	   $columns_consumer['login_day'] = date('Y-m-d');
  	   $columns_consumer['last_login'] = date('Y-m-d H:i:s');
  	   $params = array('datatype' => 'users','tbl_row_id' => $users_id, 'columns' => $columns_consumer);
  	   $api->save_pod_item($params); 
      }
    }
  }
}
add_action('wp_head', 'logged_in_points');

/* BOF Custom Buzzr */
/* Function hooks into the FB-Autoconnect login hook to check if user 
loggin in has a pod item, if not creates one for the user */
function users_new_pod_item($args)
{
  $wp_id = $args['WP_ID'];
  $users = new Pod('users');
  $users->page = 1;
  $users->search = false;
  $users->findRecords('id DESC', -1, "wp_user.id ='$wp_id'");
  $total_rows = $users->getTotalRows();
  if($total_rows == '0')
  {
    date_default_timezone_set('Asia/Kolkata');
    $api = new PodAPI();
    //$user_firstname = get_user_meta($wp_id, 'first_name', 'true');
    //$user_lastname = get_user_meta($wp_id, 'last_name', 'true');
    $user_obj = get_userdata($wp_id);
    $username = ucwords($user_obj->user_login);
    $columns_user['name'] = $username;
    $columns_user['slug'] = $columns['name'];
    $columns_user['wp_user'] =  $wp_id;
    $columns_user['login_day'] = date('Y-m-d');
	$columns_user['last_login'] = date('Y-m-d H:i:s');
    $params = array('datatype' => 'users','columns' => $columns_user);
    $api->save_pod_item($params);
    
    
    $users = new Pod('users');
    $users->page = 1;
    $users->search = false;
    $users->findRecords('id DESC', "1", "wp_user.id ='$wp_id'");
    while ($users->fetchRecord())
    {
        $users_id = $users->get_field('id');
    }
    
    $columns_points['name'] = $columns_user['name'];
    $columns_points['slug'] = $columns['name'];
    $columns_points['registration'] = '1000';
    $columns_points['login'] = '0';
    $columns_points['comments'] = '0';
    $columns_points['deals'] = '0';
    $columns_points['like_fb'] = '0';
    $columns_points['vote'] = '0';
    $columns_points['feedback'] = '0';
    $columns_points['referral'] = '0';
    $columns_points['user'] = $users_id;
    $params = array('datatype' => 'points','columns' => $columns_points);
    $api->save_pod_item($params);
  }
  elseif($total_rows == '1')
  {
    date_default_timezone_set('Asia/Kolkata');
    $users = new Pod('users');
    $users->page = 1;
    $users->search = false;
    $users->findRecords('id DESC', "1", "wp_user.id ='$wp_id'");
    while ($users->fetchRecord())
    {
        $users_id = $users->get_field('id');
	      $users_name = $users->get_field('name');
	      $login_day = $users->get_field('login_day');
    }

    $points = new Pod('points');
    $points->page = 1;
    $points->search = false;
    $points->findRecords('id DESC', "1", "user.id ='$users_id'");
    $pod_item_exits = $points->getTotalRows();

    if($pod_item_exits == 1)
    {
	    while ($points->fetchRecord())
	    {
    		$id = $points->get_field('id');
    		$login_points = $points->get_field('login');
	    }

      if(empty($login_day))
      {
        $api = new PodAPI();
  	    $columns_points['login'] = ($login_points + 50);
  	    $params = array('datatype' => 'points','tbl_row_id' => $id, 'columns' => $columns_points);
  	    $api->save_pod_item($params);
  	    $login_day_mod = date('Y-m-d');
      }
      elseif(strtotime($login_day) < strtotime(date('Y-m-d')))
      {
        $api = new PodAPI();
  	    $columns_points['login'] = ($login_points + 50);
  	    $params = array('datatype' => 'points','tbl_row_id' => $id, 'columns' => $columns_points);
  	    $api->save_pod_item($params);
  	    $login_day_mod = date('Y-m-d');
      }
      
      $api = new PodAPI();
	    if(!empty($login_day_mod))
	    {
        $columns_consumer['login_day'] = $login_day_mod; 
      }
      $columns_consumer['last_login'] = date('Y-m-d H:i:s');
	    $params = array('datatype' => 'users','tbl_row_id' => $users_id, 'columns' => $columns_consumer);
	    $api->save_pod_item($params); 
    }
    else
    {
   	   $api = new PodAPI();
	   $columns_points['name'] = $users_name;
	   $columns_points['slug'] = $users_name;
	   $columns_points['registration'] = '1000';
	   $columns_points['login'] = '50';
	   $columns_points['comments'] = '0';
	   $columns_points['deals'] = '0';
	   $columns_points['like_fb'] = '0';
	   $columns_points['vote'] = '0';
	   $columns_points['feedback'] = '0';
	   $columns_points['referral'] = '0';
	   $columns_points['user'] = $users_id;
	   $params = array('datatype' => 'points','columns' => $columns_points);
	   $api->save_pod_item($params);
	   
	   $columns_consumer['login_day'] = date('Y-m-d');
	   $columns_consumer['last_login'] = date('Y-m-d H:i:s');
	   $params = array('datatype' => 'users','tbl_row_id' => $users_id, 'columns' => $columns_consumer);
	   $api->save_pod_item($params); 
    }
  }
}
add_action('wpfb_login', 'users_new_pod_item');
/* BOF Custom Buzzr */

/* Buzzr Custom Login Logo */
function buzzr_custom_login_logo() {
    echo "<style> body{ margin: 0 auto 0 auto; width: 400px; } h1 a { background-image:url('http://buzzr.in/wp-content/themes/buzzr_960/img/buzzrin-logo.png') !important; } </style>";
}
add_action('login_head', 'buzzr_custom_login_logo');
/* Buzzr Custom Login Logo */

/* Buzzr Get Image Against a Deal */
function get_image($deal_record, $size = 'thumbnail'){
	$image = $deal_record->get_field('image');
	if(!empty($image)){
	    $small_image =  wp_get_attachment_image_src($image[0][ID], $size, false);
	    $small_image = $small_image[0];
	    return $small_image;
	}else{
    	$small_image = $deal_record->get_field('ext_image_url');
    	return $small_image;
    }
    
    if(!empty($small_image)){
    	return $small_image;
    }else{
    	$image = $deal_record->get_field('brand.logo');
    	$small_image =  wp_get_attachment_image_src($image[0][ID], $size, false);
	    $small_image = $small_image[0];	
    }
    
    if(!empty($small_image)){
    	return $small_image;
    }else{
    	return FALSE;
    }
}
/* Buzzr Get Image Against a Deal */
function get_redirect($deal_record, $brand_name = ''){
	session_start();
	unset($_SESSION['local']);
	$_SESSION['local'] = 0;
	$deal_quickcamp = $deal_record->get_field('quickcamp');
	$deal_sale = $deal_record->get_field('sale');
	$is_daily = $deal_record->get_field('daily');
	$is_coupon = $deal_record->get_field('coupon');
	$ext_link = $deal_record->get_field('extlink');
	if(empty($brand_name)){
		$brand_name = $deal_record->get_field('brand.name');
	}
	$camp_name = $deal_record->get_field('name');
	$deal_link = BUZZR_URL.'/deals/'.$deal_record->get_field('camp_link');
	
	if($deal_quickcamp == 1){
	  if(!empty($ext_link)){
	  $event = 'Online Deals~'.ucwords($brand_name).'~'.$camp_name.'~'.$ext_link;
	  $event = encrypt($event,'1b2u3z4z5r6');
	  $grab_deal = BUZZR_WP_URL.'/wp-content/plugins/buzzr_tracking/redirect.php?p='.$event;
	  }
	  else{
	  $grab_deal = $deal_link;
	  }
	  return $grab_deal;
	}
	
	if($is_daily == 1){
	  if(!empty($ext_link)){
	  $event = 'Online Daily Deals~'.ucwords($brand_name).'~'.$camp_name.'~'.$ext_link;
	  $event = encrypt($event,'1b2u3z4z5r6');
	  $grab_deal = BUZZR_WP_URL.'/wp-content/plugins/buzzr_tracking/redirect.php?p='.$event;
	  }
	  else{
	  $grab_deal = $deal_link;
	  }
	  return $grab_deal;
	}
	
	if($deal_sale == 1){
	  if(!empty($ext_link)){
	  $event = 'Local Deal~'.ucwords($brand_name).'~'.$camp_name.'~'.$ext_link;
	  $event = encrypt($event,'1b2u3z4z5r6');
	  $grab_deal = BUZZR_WP_URL.'/wp-content/plugins/buzzr_tracking/redirect.php?p='.$event;
	  }
	  else{
	  $grab_deal = $deal_link;
	  $_SESSION['local'] = 1;
	  }
	  return $grab_deal;
	}
	
	if($is_coupon == 1){
	  if(!empty($ext_link)){
	  $event = 'Coupon Deals~'.ucwords($brand_name).'~'.$camp_name.'~'.$ext_link;
	  $event = encrypt($event,'1b2u3z4z5r6');
	  $grab_deal = BUZZR_WP_URL.'/wp-content/plugins/buzzr_tracking/redirect.php?p='.$event;
	  }
	  else{
	  $grab_deal = $deal_link;
	  }
	  return $grab_deal;
	}
}

/* BOF buzzr_follow */
/* Outputs nofollow attribute for deals with external links */
function buzzr_follow(){
	if(isset($_SESSION['local'])){
      	$is_local = $_SESSION['local'];
      	if($is_local == 0){
      		echo 'rel="nofollow" target="_blank"';
      	}
	}
}
/* EOF buzzr_follow */

function get_city(){
	ob_start();
	$city_name = $_GET['city'];
	if(!empty($city_name)){
		setcookie("city", "", time()-3600);
		setcookie("city", $city_name, time()+2592000);
		unset($_SESSION['city']);
		session_start();
		$_SESSION['city']= $city_name;
		return $city_name;
	}elseif(!empty($_COOKIE["city"])){
		return $_COOKIE["city"];
	}elseif(!empty($_SESSION['city'])){
		return $_SESSION['city'];
	}else{
		return 'Mumbai';
	}
}

/**
 * xml2array() will convert the given XML text to an array in the XML structure.
 * Link: http://www.bin-co.com/php/scripts/xml2array/
 * Arguments : $contents - The XML text
 *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
 *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
 * Examples: $array =  xml2array(file_get_contents('feed.xml'));
 *              $array =  xml2array(file_get_contents('feed.xml', 1, 'attribute'));
 */
function xml2array($contents, $get_attributes=1, $priority = 'tag') {
    if(!$contents) return array();

    if(!function_exists('xml_parser_create')) {
        //print "'xml_parser_create()' function not found!";
        return array();
    }

    //Get the XML parser of PHP - PHP must have this module for the parser to work
    $parser = xml_parser_create('');
    xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    xml_parse_into_struct($parser, trim($contents), $xml_values);
    xml_parser_free($parser);

    if(!$xml_values) return;//Hmm...

    //Initializations
    $xml_array = array();
    $parents = array();
    $opened_tags = array();
    $arr = array();

    $current = &$xml_array; //Refference

    //Go through the tags.
    $repeated_tag_index = array();//Multiple tags with same name will be turned into an array
    foreach($xml_values as $data) {
        unset($attributes,$value);//Remove existing values, or there will be trouble

        //This command will extract these variables into the foreach scope
        // tag(string), type(string), level(int), attributes(array).
        extract($data);//We could use the array by itself, but this cooler.

        $result = array();
        $attributes_data = array();
        
        if(isset($value)) {
            if($priority == 'tag') $result = $value;
            else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
        }

        //Set the attributes too.
        if(isset($attributes) and $get_attributes) {
            foreach($attributes as $attr => $val) {
                if($priority == 'tag') $attributes_data[$attr] = $val;
                else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
            }
        }

        //See tag status and do the needed.
        if($type == "open") {//The starting of the tag '<tag>'
            $parent[$level-1] = &$current;
            if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
                $current[$tag] = $result;
                if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
                $repeated_tag_index[$tag.'_'.$level] = 1;

                $current = &$current[$tag];

            } else { //There was another element with the same tag name

                if(isset($current[$tag][0])) {//If there is a 0th element it is already an array
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    $repeated_tag_index[$tag.'_'.$level]++;
                } else {//This section will make the value an array if multiple tags with the same name appear together
                    $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
                    $repeated_tag_index[$tag.'_'.$level] = 2;
                    
                    if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
                        $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                        unset($current[$tag.'_attr']);
                    }

                }
                $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
                $current = &$current[$tag][$last_item_index];
            }

        } elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
            //See if the key is already taken.
            if(!isset($current[$tag])) { //New Key
                $current[$tag] = $result;
                $repeated_tag_index[$tag.'_'.$level] = 1;
                if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;

            } else { //If taken, put all things inside a list(array)
                if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array...

                    // ...push the new element into that array.
                    $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    
                    if($priority == 'tag' and $get_attributes and $attributes_data) {
                        $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                    }
                    $repeated_tag_index[$tag.'_'.$level]++;

                } else { //If it is not an array...
                    $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
                    $repeated_tag_index[$tag.'_'.$level] = 1;
                    if($priority == 'tag' and $get_attributes) {
                        if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
                            
                            $current[$tag]['0_attr'] = $current[$tag.'_attr'];
                            unset($current[$tag.'_attr']);
                        }
                        
                        if($attributes_data) {
                            $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                        }
                    }
                    $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken
                }
            }

        } elseif($type == 'close') { //End of tag '</tag>'
            $current = &$parent[$level-1];
        }
    }
    
    return($xml_array);
}  
/* xml2array() will convert the given XML text to an array in the XML structure. */

/* make a URL small */
/* usage */
//$short = make_bitly_url('http://davidwalsh.name','davidwalshblog','R_96acc320c5c423e4f5192e006ff24980','json');
//echo 'The short URL is:  '.$short;
// returns:  http://bit.ly/11Owun
function make_bitly_url($url,$login = 'kunal17',$appkey = 'R_a723c15700f18b2b612494500eab6caf',$format = 'json',$version = '2.0.1')
{
  //create the URL
	$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;
  //get the url
	//could also use cURL here
	$response = file_get_contents($bitly);
	
	//parse depending on desired format
	if(strtolower($format) == 'json')
	{
		$json = @json_decode($response,true);
		return $json['results'][$url]['shortUrl'];
	}
	else //xml
	{
		$xml = simplexml_load_string($response);
		return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
	}
}

/* make a URL small using google url shortner, account with enthrallmedia@gmail.com */
function make_goog_url($url)
{
  $longURLData = array('longUrl' => $url);
 
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_URL, 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAg_Lv8VKWuDlfEbjuu0235TfyL0cjwQHk');
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
  curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($longURLData));
  $jsonResult = curl_exec($curl);
  curl_close($curl);
 
  $resultArray = json_decode($jsonResult, true);
  
  return $resultArray['id'];
}
/* make a URL small using google url shortner, account with enthrallmedia@gmail.com */

function check_daily_category($deal_title)
{
$cat['c-restaurants-clubs-offers'] = array('food','restaurant','brunch','meal','drinks','eat','breakfast','coffee','cappuccino','ice','cream','cuisine','egg','pub','pubs','juice','juices','veg','non-veg','dine','buffet','pizza','pizzas','beverage','beverages','biryani','soup','chicken');
$cat['c-health-and-beauty-offers'] = array('spa','massage','relaxation','gym','fitness','tattoo','dental','haircut','nail','ayurveda','hair','beauty','therapy','care');
$cat['c-flowers-gifts-offers'] = array('flowers','customized','gift','cake');
$cat['c-entertainment-offers'] = array('movie','concert','show','performance','event');
$cat['c-services-offers'] = array('amc','maintainence','service','services','classes');
$cat['c-shopping-offers'] = array('furnishing','kurta','tunic','sale','kid','shop','voucher','vouchers','perfume');

unset($string);
$string = strtolower($deal_title);

$max = array(null, 0); // category, occurences
foreach($cat as $k => $v) {
  $replaced = str_replace($v, '##########', $string);
  preg_match_all('/##########/i', $replaced, $matches);
  if(count($matches[0]) > $max[1]) {
    $max[0] = $k;
    $max[1] = count($matches[0]);
  }
}

//echo "Category {$max[0]} has the most ({$max[1]}) matches.\n";
if(!empty($max[0]) && $max[1] > 0)
{
$cat_pod = new Pod('category');
$cat_pod->search = false;
$cat_pod->page = 1;
$cat_pod->findRecords('id DESC', -1, "t.url='$max[0]'");
unset($cat_id);
while($cat_pod->fetchRecord())
{
  $cat_id = $cat_pod->get_field('id');
}

}
//echo $cat_id;
return $cat_id;
}

/* Returns Time Remaning in Simple English */
function time_till_expires($value){
date_default_timezone_set('Asia/Kolkata');
$enddate = date("U", strtotime($value));
$today = time();
    
// array of time period chunks
$chunks = array(
    (60 * 60 * 24 * 365),
    (60 * 60 * 24 * 30),
    (60 * 60 * 24 * 7),
    (60 * 60 * 24),
    (60 * 60),
    (60),
    (1)
);

$till = $enddate - $today;

for ($i = 0, $j = count($chunks); $i < $j; $i++) {
    $seconds = $chunks[$i];

    if (0 != $count = floor($till / $seconds))
        break;
}

$trans = array(
    _n('%d year', '%d years', $count),
    _n('%d month', '%d months', $count),
    _n('%d week', '%d weeks', $count),
    _n('%d day', '%d days', $count),
    _n('%d hour', '%d hours', $count),
    _n('%d minute', '%d minutes', $count),
    _n('%d second', '%d seconds', $count)
);

if ('0000-00-00 00:00:00' == $value) {
    $result = 'No Expiry';
}
elseif ($today >= $enddate) {
    $result = 'This offer has expired';
}
else {
    $output = sprintf($trans[$i], $count);
    $result = 'This offer expires in '.$output;
}

return $result;
}
/* Returns Time Remaning in Simple English */

/* BOF Custom Buzzr
Function Uses Data Dumped by the custom file placed inside wp-content/plugins/google-xml-sitemap/buzzr_sitemap.php
from file located as /var/www/buzzr1/buzzr_sitemap.xml
attaches the data after using unserialize to the Google XML sitemap Generator object, which is called everytime the the sitemap is regenerated, thus makin a combined XML file of WP + PODS :)
*/ 
function pods_pages() {
$file = '/var/www/html/buzzr1/buzzr_sitemap.xml';
$fileHandle = fopen($file, "rb");
$fileContents = fread($fileHandle, filesize($file));
fclose($fileHandle);
$links = unserialize($fileContents);

$count = count($links['url']);
$generatorObject = &GoogleSitemapGenerator::GetInstance(); //Please note the "&" sign for PHP4!
if($generatorObject != null){
	for($i=0; $i<$count; $i++)
	{
	    $generatorObject->AddUrl($links['url'][$i],$links['last_mod'][$i],$links['change_freq'][$i],$links['priority'][$i]);
	}
}

}
add_action("sm_buildmap","pods_pages");

/* EOF Custom Buzzr */

/* Detect if User added the Deal, so he can edit */
function is_deal_owner($added_by_user_slug){
    $loggedin_user_slug = get_buzzr_users_pod_id('','slug');

	if($loggedin_user_slug == $added_by_user_slug){
		$is_owner_of_offer = 1;
	}else{
		$is_owner_of_offer = 0;
	}
	return $is_owner_of_offer;
}
/* Detect if User added the Deal, so he can edit */

/* One stop function to give users details */ 
function buzzrs_current_user(){
	if (is_user_logged_in()){
		global $current_user;
		get_currentuserinfo();
		
		$user_wp_id = $current_user->ID;
		$user_roles = $current_user->roles;
		$user_role = array_shift($user_roles);
		
		$users = new Pod('users');
		$users->page = 1;
		$users->search = false;
		$users->findRecords('id DESC',1,"wp_user.ID='$user_wp_id'");
		while($users->fetchRecord()){
			$buzzrs_user['wpid'] = $user_wp_id;
			$buzzrs_user['user_id'] = $users->get_field('id');
			$buzzrs_user['points_id'] = $users->get_field('points.id');
			$buzzrs_user['newsletter_id'] = $users->get_field('newsletter_pod.id');
			$buzzrs_user['name'] = $users->get_field('name');
			$buzzrs_user['short_name'] = substr($users->get_field('name'),0,10);
      
      $name_space = strpos($buzzrs_user['name'], " ");
			$name_dot = strpos($buzzrs_user['name'], ".");
			if($name_space !== false){
			   $first_name = explode(" ",$buzzrs_user['name']);
			   $buzzrs_user['short_name'] = substr($first_name[0],0,12);
			}
			
      if($name_dot !== false){
			   $first_name = explode(".",$buzzrs_user['name']);
			   $buzzrs_user['short_name'] = substr($first_name[0],0,12);
			}
			
			$buzzrs_user['slug'] = $users->get_field('slug');
			$buzzrs_user['is_affiliate'] = $users->get_field('paid_affiliate');
			$buzzrs_user['deals_liked'] = $users->get_field('deals_liked.id');
			
			$user_points_reg = $users->get_field('points.registration');
			$user_points_login = $users->get_field('points.login');
			$user_points_comments = $users->get_field('points.comments');
			$user_points_deals = $users->get_field('points.deals');
			$user_points_like_fb = $users->get_field('points.like_fb');
			$user_points_feedback = $users->get_field('points.feedback');
			$user_points_vote = $users->get_field('points.vote');
			$user_points_referral = $users->get_field('points.referral');
			$total_points = $user_points_reg + $user_points_login + $user_points_comments + $user_points_deals + $user_points_like_fb + $user_points_feedback + $user_points_vote + $user_points_referral;
			
			$buzzrs_user['total_points'] = $total_points;
			$buzzrs_user['profile_pic'] = get_avatar($user_wp_id,'30');
			$buzzrs_user['profile_link'] = BUZZR_URL.'/member/'.$buzzrs_user['slug'];
			
			if(!empty($buzzrs_user['newsletter_id'])){
				$buzzrs_user['newsletter_slug'] = $users->get_field('newsletter_pod.slug');
				$encrypted_slug = encrypt($buzzrs_user['newsletter_slug'],'1b2u3z4z5r6');
				$buzzrs_user['email_pref_link'] = 'http://buzzr.in/emailpref/?p='.$encrypted_slug;
			}
			
			if($user_role == 'moderator' || $user_role == 'administrator'){
				$buzzrs_user['is_admin'] = '1';
				$buzzrs_user['stats'] = BUZZR_URL.'/buzzr_stats.php';
				$buzzrs_user['new_brand'] = BUZZR_URL.'/admin/newbrand';
				$buzzrs_user['new_coupon'] = BUZZR_URL.'/admin/newcoupon';
				$buzzrs_user['new_daily'] = BUZZR_URL.'/admin/newdaily';
				$buzzrs_user['new_deal'] = BUZZR_URL.'/admin/newdeal';
                $buzzrs_user['categories'] = BUZZR_URL.'/admin/catdaily';
			}
		}
	}
	return $buzzrs_user;
}
/* One stop function to give users details */

/* Buzzr Array Order By function, used for sorting a multidimensional array by 2 parameters,
usage as explained in example below in comment */
/* $sorted = array_orderby($user, 'total_points', SORT_DESC, 'modified', SORT_ASC); */
function array_orderby()
{
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row)
                $tmp[$key] = $row[$field];
            $args[$n] = $tmp;
            }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}
/* Buzzr Array Order By function */

function buzzr_saved_deal($deals_liked,$deal_id){
	$user_already_likes = 0;
	if(is_array($deals_liked)){
		if(in_array($deal_id, $deals_liked)){
       			$user_already_likes = 1;
    		}
  	}
  	else{
    		if($deals_liked == $deal_id){
       			$user_already_likes = 1;
    		}
  	}
  	return $user_already_likes;
}
?>
